package com.magicborrow.adapter;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.magicborrow.Constants;
import com.magicborrow.R;
import com.magicborrow.activity.BorrowStuffDetailActivity;
import com.magicborrow.activity.NewPhoneActivity;
import com.magicborrow.activity.PayActivity;
import com.magicborrow.beans.ApplyEntity;
import com.magicborrow.enums.PriceModeEnum;
import com.magicborrow.huanxin.ChatActivity;
import com.magicborrow.utils.ImageLoadUtil;
import com.magicborrow.utils.UserTools;
import com.magicborrow.utils.VolleyTool;
import com.magicborrow.view.ContactDialog;
import com.magicborrow.views.MsgDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by ghost on 16/3/28.
 */
public class ApplySendAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private static final int TYPE_FOOT = 0;
    private static final int TYPE_NORMAL = 1;
    private ArrayList<ApplyEntity.ContentData> mData;
    private Activity mContext;
    private LayoutInflater mLayoutInflater;

    public ApplySendAdapter(Activity pContext) {
        this.mContext = pContext;
        mLayoutInflater = LayoutInflater.from(mContext);
    }

    public void setData(ArrayList<ApplyEntity.ContentData> pData) {
        this.mData = pData;
    }

    public ArrayList<ApplyEntity.ContentData> getData() {
        return this.mData;
    }

    @Override
    public int getItemViewType(int position) {
        if (position + 1 == getItemCount()) {
            return TYPE_FOOT;
        } else {
            return TYPE_NORMAL;
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TYPE_FOOT) {
            View view = mLayoutInflater.inflate(R.layout.load_more_footer, null);
            view.setTag("foot");
            return new FootViewHolder(view);
        } else if (viewType == TYPE_NORMAL) {
            View view = mLayoutInflater.inflate(R.layout.apply_send_item, null);
            return new ApplySendItemViewHolder(view);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        if (holder instanceof ApplySendItemViewHolder) {
            final ApplySendItemViewHolder hold = (ApplySendItemViewHolder) holder;
            final ApplyEntity.ContentData bean = mData.get(position);
            Log.e("ssss", Constants.ADDRESS + bean.getTarget().getAvatar80());
            ImageLoadUtil.loadImage(hold.imv_head, Constants.ADDRESS + bean.getTarget().getAvatar80().split("\\?")[0], R.mipmap.head_default);
            String url = "";
            if (bean.getWare().getImages() != null && bean.getWare().getImages().size() > 0) {
                url = Constants.ADDRESS + bean.getWare().getImages().get(0).getPreview();
            }
            ImageLoadUtil.loadImage(hold.good_pic, url, R.mipmap.img_default);
            hold.good_name.setText(bean.getWare().getName());
            hold.tv_name.setText(bean.getTarget().getNickname());
            hold.tv_address.setText("地址: " + bean.getWare().getAddress());
            hold.borrowTime.setText("借用时间: " + bean.getCreated());
            hold.borrowShichang.setText("借用时长: " + bean.getNumber() + PriceModeEnum.getModeStr(bean.getWarePriceMode()));
            float lendScaleAVG = bean.getTarget().getLendScaleAVG();//借出者的信用评分
            //hold.commentCountMsg.setText(lendScaleAVG + "分");
            hold.commentCountMsg.setText(lendScaleAVG+"分 ("+bean.getCommented()+"人评价)");
            hold.rb_pingfen.setRating(lendScaleAVG);
            hold.shouldPay.setText("应付金额: " + (bean.getNumber() * bean.getWarePrice() + bean.getWareDeposit()));
            operateStatus(bean.getStatus(), hold.statusMsg, hold.leftStatus, hold.rightStatus, hold.statusLayout);
            hold.leftStatus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int status = bean.getStatus();
                    String lm = hold.leftStatus.getText().toString();
                    if ("联系TA".equals(lm)) {
                        ContactDialog contactDialog = new ContactDialog(mContext
                                ,bean.getTarget().getNickname()
                                ,bean.getTarget().getId()
                                ,bean.getTarget().getMobile()
                                , bean.getTarget().getAvatar80());
                        contactDialog.show();
                     /*   mContext.startActivity(new Intent(mContext, ChatActivity.class).putExtra("chatType", 1)
                                .putExtra("userId", bean.getTarget().getId() + "")
                                .putExtra("username", bean.getTarget().getNickname()).putExtra("avatarPath",
                                        bean.getTarget().getAvatar80()));*/
                    } else {
                        if (status == 1 && "去付款".equals(lm)) {
                            //  在这里调用付款的玩意
                            Intent intent = new Intent();
                            intent.putExtra("data", bean);
                            intent.setClass(mContext, PayActivity.class);
                            mContext.startActivity(intent);
                        } else if (status == 5 && "同意取消".equals(lm)) {
                            new SendRequest(bean, 9, position, "同意取消请求已发送成功!").sendRequest();
                        } else if (status == 99 && "重新申请".equals(lm)) {
                            sendRequest1(bean.getId(), 0, position, "请求发送成功!");
                        }
                    }

                }
            });
            hold.rightStatus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int status = bean.getStatus();
                    String rm = hold.rightStatus.getText().toString();
                    if ((status == 0 || status == 1) && "取消借用".equals(rm)) {
                        new SendRequest(bean, 99, position, "申请取消借用请求已发送成功!").sendRequest();
                    }else if( status == 3 && "取消借用".equals(rm)){
                        new SendRequest(bean, 99, position, "申请取消借用请求已发送成功!").sendRequest();
                    } else if (status == 5 && "拒绝取消".equals(rm)) {
                        new SendRequest(bean, 6, position, "您已经拒绝取消!").sendRequest();
                    } else if (status == 99 && "删除".equals(rm)) {
                        sendRequest1(bean.getId(), 1, position, "");
                        }else if(status == 8 && "确认收到".equals(rm)){
                        new SendRequest(bean, 9, position, "您已确认收到货物!").sendRequest();
                    }
                }
            });
        }
    }

    private ProgressDialog progressDialog = null;

    class SendRequest {
        ApplyEntity.ContentData bean;
        int cStatus;
        int position;
        String msg;

        public SendRequest(ApplyEntity.ContentData bean, int cStatus, int position, String msg) {
            this.bean = bean;
            this.cStatus = cStatus;
            this.position = position;
            this.msg = msg;
        }

        public void sendRequest() {
            progressDialog = new ProgressDialog(mContext);
            progressDialog.show();
            Map<String, String> params = new HashMap<>();
            params.put("id", bean.getId() + "");
            params.put("status", cStatus + "");
            params.put("acc_token", UserTools.getUser(mContext).getAcc_token());
            VolleyTool.get(Constants.FLOW_CONTROL, params, new VolleyTool.HTTPListener() {
                @Override
                public <T> void onResponse(T t, int requestCode) {
                    progressDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(t.toString());
                        int code = json.getInt("code");
                        if (code == 0) {
                            new MsgDialog(mContext, msg, null).show();
                            mData.get(position).setStatus(cStatus);
                            ApplySendAdapter.this.notifyItemChanged(position);
                        }
                    } catch (JSONException e) {
                        // e.printStackTrace();
                    }
                }

                @Override
                public void onErrorResponse(VolleyError error, int requestCode) {
                    progressDialog.dismiss();
                    Toast.makeText(mContext, "服务器暂时无法链接", Toast.LENGTH_SHORT).show();
                }
            }, 0, null);
        }
    }

    private void sendRequest1(int id, final int type, final int position, final String msg) {
        progressDialog = new ProgressDialog(mContext);
        progressDialog.show();
        Map<String, String> params = new HashMap<>();
        params.put("id", id + "");
        params.put("acc_token", UserTools.getUser(mContext).getAcc_token());
        String url = "";
        if (type == 0) {
            url = Constants.APPLY_AGAIN_URL;
        } else {
            url = Constants.DELETE_ORDER_URL;
        }
        VolleyTool.get(url, params, new VolleyTool.HTTPListener() {
            @Override
            public <T> void onResponse(T t, int requestCode) {
                progressDialog.dismiss();
                try {
                    JSONObject json = new JSONObject(t.toString());
                    int code = json.getInt("code");
                    if (code == 0) {
                        if (!"".equals(msg)) {
                            new MsgDialog(mContext, msg, null).show();
                        }
                        if (type == 0) {
                            mData.get(position).setStatus(0);
                            ApplySendAdapter.this.notifyDataSetChanged();
                        } else {
                            mData.remove(mData.get(position));
                            ApplySendAdapter.this.notifyDataSetChanged();
                        }
                    }
                } catch (JSONException e) {
                    // e.printStackTrace();
                }
            }

            @Override
            public void onErrorResponse(VolleyError error, int requestCode) {
                progressDialog.dismiss();
                Toast.makeText(mContext, "服务器暂时无法链接", Toast.LENGTH_SHORT).show();
            }
        }, 0, null);
    }

    private void operateStatus(int status, TextView statusMsg, TextView leftStatus, TextView rightStatus, RelativeLayout statusLayout) {
        String sStatusMsg = "";
        String sLeftStatus = "";
        String sRightStatus = "";
        switch (status) {
            case 0:
                sStatusMsg = "等待物主同意";
                sLeftStatus = "联系TA";// 私信
                sRightStatus = "取消借用";
                statusLayout.setVisibility(View.VISIBLE);
                break;
            case 1:
                sStatusMsg = "物主已同意,请付款";
                sLeftStatus = "去付款";// 付款详情页面
                sRightStatus = "取消借用";
                statusLayout.setVisibility(View.VISIBLE);
                break;
            case 2:
                sStatusMsg = "物主已经拒绝您的请求";
                sLeftStatus = "联系TA"; // 私信
                sRightStatus = " ";// 不可点击
                statusLayout.setVisibility(View.VISIBLE);
                break;
            case 3:
                sStatusMsg = "已付款";
                sLeftStatus = "联系TA";
                sRightStatus = "取消借用";
                statusLayout.setVisibility(View.VISIBLE);
                break;
            case 4:
                sStatusMsg = "已申请取消借用";
                sLeftStatus = "联系TA";
                sRightStatus = " ";  // 不可点击
                statusLayout.setVisibility(View.VISIBLE);
                break;
            case 5:
                sStatusMsg = "物主申请取消";
                sLeftStatus = "同意取消";
                sRightStatus = "拒绝取消";
                statusLayout.setVisibility(View.VISIBLE);
                break;
            case 6:
                sStatusMsg = "我已拒绝取消";
                sLeftStatus = "联系TA";
                sRightStatus = " ";// 不可点击
                statusLayout.setVisibility(View.VISIBLE);
                break;
            case 7:
                sStatusMsg = "物主拒绝取消";
                sLeftStatus = "联系TA";
                sRightStatus = " ";// 不可点击
                statusLayout.setVisibility(View.VISIBLE);
                break;
            case 8:
                sStatusMsg = "申请借用成功";
                sLeftStatus = "联系TA";
                sRightStatus = "确认收到";
                break;
            case 9:
                sStatusMsg = "确认收到";
                sLeftStatus = "联系TA";
                sRightStatus = " ";
                statusLayout.setVisibility(View.VISIBLE);
                break;
            case 99:
                sStatusMsg = "已取消";
                sLeftStatus = "重新申请";
                sRightStatus = "删除";
                statusLayout.setVisibility(View.VISIBLE);
                break;
        }
        statusMsg.setText(sStatusMsg);
        leftStatus.setText(sLeftStatus);
        rightStatus.setText(sRightStatus);
    }

    @Override
    public int getItemCount() {
        return mData.size() + 1;
    }


    public class ApplySendItemViewHolder extends RecyclerView.ViewHolder {
        private ImageView imv_head;
        private TextView tv_name;
        private TextView statusMsg;
        private RatingBar rb_pingfen;
        private TextView commentCountMsg;
        private ImageView good_pic;
        private TextView good_name;
        private TextView borrowTime;
        private TextView borrowShichang;
        private TextView tv_address;
        private TextView shouldPay;
        private TextView leftStatus;
        private TextView rightStatus;
        private RelativeLayout statusLayout;

        public ApplySendItemViewHolder(View view) {
            super(view);
            statusLayout = (RelativeLayout) view.findViewById(R.id.statusLayout);
            imv_head = (ImageView) view.findViewById(R.id.imv_head);
            tv_name = (TextView) view.findViewById(R.id.tv_name);
            statusMsg = (TextView) view.findViewById(R.id.statusMsg);
            rb_pingfen = (RatingBar) view.findViewById(R.id.rb_pingfen);
            commentCountMsg = (TextView) view.findViewById(R.id.commentCountMsg);
            good_pic = (ImageView) view.findViewById(R.id.good_pic);
            good_name = (TextView) view.findViewById(R.id.good_name);
            borrowTime = (TextView) view.findViewById(R.id.borrowTime);
            borrowShichang = (TextView) view.findViewById(R.id.borrowShichang);
            tv_address = (TextView) view.findViewById(R.id.tv_address);
            shouldPay = (TextView) view.findViewById(R.id.shouldPay);
            leftStatus = (TextView) view.findViewById(R.id.leftStatus);
            rightStatus = (TextView) view.findViewById(R.id.rightStatus);
        }
    }

    public class FootViewHolder extends RecyclerView.ViewHolder {

        public FootViewHolder(View itemView) {
            super(itemView);
        }

    }


}
